<template>
  <div>
    <div class="center-pane narrow">
      <h3 class="title">导入开源工程</h3>
      <el-form :rules="rules" :model="form" ref="importForm">
        <el-form-item label="代码仓库地址" prop="url">
          <el-input v-model="form.url" @input="onInput"></el-input>
        </el-form-item>
        <el-form-item label="工程名称">
          <el-input v-model="form.name" placeholder="如果不填写，则使用代码仓库的名称"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="form.desc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">导入</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        url: '',
        name: '',
        desc: ''
      },
      rules: {
        url: [
          { required: true, message: "请输入代码仓库URL", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    onInput() {
      // 从URL中解析出项目名称
      let u = new URL(this.form.url);
        /*
        let paths = u.pathname.split('/')
        if (paths.length > 0) {
          let last = paths[paths.length - 1]
          this.form.name = last;
        }
        */
      this.form.name = u.pathname;
      this.form.source = u.hostname;
    },
    onSubmit() {
      this.$refs["importForm"].validate((valid) => {
        if (valid) {
          console.log("submitting:", JSON.stringify(this.form));
          this.authPost("/api/v1/mats/projects/import", this.form).then(res => {
            console.log("import res: ", res)
            this.$router.push("/coding");
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancel() {
      this.$router.push("/coding");
    }
  },
};
</script>